package com.example.demo2

import android.annotation.SuppressLint
import android.os.Bundle
import android.os.Handler
import android.util.Log
import android.view.Gravity
import android.widget.LinearLayout
import androidx.appcompat.app.AppCompatActivity
import io.zhuozhuo.remotetestlib.DataCenter
import io.zhuozhuo.remotetestlib.Message
import kotlinx.android.synthetic.main.activity_main.*

class MainActivity : AppCompatActivity() {
    private val tag = this.javaClass.name

    private val mHandler = @SuppressLint("HandlerLeak")
    object : Handler() {
        override fun handleMessage(msg: android.os.Message) {
            super.handleMessage(msg)
            addMessage(msg.obj as Message)
        }
    }

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        DataCenter.register { list ->
            //Log.d("size:", list.size.toString())
            for (i in 0 until list.size) {
                val item = list[i]
                if (item.msgType != Message.MessageTypeText) continue
                val hMsg = android.os.Message.obtain()
                hMsg.obj = list[i]
                mHandler.sendMessageDelayed(hMsg, 1000)
            }
        }
    }

    private fun addMessage(message: Message?) {
        if (message == null) return
        Log.d(tag, message.content)
        val item = LinearLayout(this)
        item.gravity = Gravity.END
        item.layoutParams = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.MATCH_PARENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        val size = MessageView.Size(
            message_text_size = 20f,
            message_text_max_width = 100,
            message_image_max_width = 200,
            message_image_max_height = 400
        )
        val child = MessageView(this, message, size)
        val lp = LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )
        if (message.msgType == Message.MessageTypeText) {
            lp.width = size.message_text_max_width
            lp.height = size.message_text_max_width
        }
        if (message.msgType == Message.MessageTypeImage) {
            lp.width = size.message_image_max_width
            lp.height = size.message_image_max_height
        }
        lp.setMargins(
            0,
            size.message_vertical_margin,
            size.message_horizontal_margin,
            size.message_vertical_margin
        )
        child.layoutParams = lp
        item.addView(child)
        ll_content.addView(item)
    }
}